package logic

import (
	"context"

	"mail/service/property/rpc/property"
	"mail/service/receipt/api/internal/svc"
	"mail/service/receipt/api/internal/types"
	"mail/service/receipt/rpc/receipt"

	"github.com/dtm-labs/dtmgrpc"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

// dtm 服务的 etcd 注册地址
var dtmServer = "etcd://etcd:2379/dtmservice"

type ConceptLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewConceptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConceptLogic {
	return &ConceptLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ConceptLogic) Concept(req *types.ConceptRequest) (resp *types.ConceptResponse, err error) {
	// todo: add your logic here and delete this line

	// 获取票据rpc buildTarget
	receiptRpcServer, err := l.svcCtx.Config.ReceiptRpc.BuildTarget()
	if err != nil {
		return nil, status.Error(100, "receipt concept error.")
	}
	propertyRpcServer, err := l.svcCtx.Config.PropertyRpc.BuildTarget()
	if err != nil {
		return nil, status.Error(100, "receipt concept error.")
	}

	//创建一个组
	gid := dtmgrpc.MustGenGid(dtmServer)
	//创建一个saga协议的事务
	saga := dtmgrpc.NewSagaGrpc(dtmServer, gid).Add(
		receiptRpcServer+"/receiptclient.Receipt/Concept",
		receiptRpcServer+"/receiptclient.Receipt/ConceptRevert",
		&receipt.ConceptRequest{
			Uid:    req.Uid,
			Pid:    req.Pid,
			Amount: req.Amount,
			Status: 0,
		},
	).Add(
		propertyRpcServer+"/propertyclient.Property/CurtailStock",
		propertyRpcServer+"/propertyclient.Property/CurtailStockRevert",
		&property.StockRequest{
			Id:  req.Pid,
			Num: 1,
		},
	)

	err = saga.Submit()
	if err != nil {
		return nil, status.Error(500, err.Error())
	}

	return &types.ConceptResponse{}, nil
}
